package cn.itsource.ymcc.filter;

import cn.itsource.ymcc.config.ExcludeProperties;
import cn.itsource.ymcc.jwt.*;
import cn.itsource.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;
import java.util.List;

/**
 * 身份认证拦截：
 *  获取请求头中的U-TOKEN，利用JWT工具类使用公钥解密，判断载荷数据非空
 */
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Value("${jwt.rsa.pub}")
    private String pub;
    @Autowired
    private ExcludeProperties properties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //响应对象
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer buffer = null;
        try {
            //0.放行yml配置中配置的需要放行的所有接口地址
            if(properties.isExcluded(exchange.getRequest().getPath().value())){
                return chain.filter(exchange);
            }
            //1.获取请求头
            List<String> headers = exchange.getRequest().getHeaders().get(LoginContextUtils.JWT_TOKEN_NAME);
            if(headers != null && headers.size() > 0){
                String jwtToken = headers.get(0);
                //2.利用jwt工具类 公钥解密
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pub).getFile());
                Payload<PayloadData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, PayloadData.class);
                if(payload != null && payload.getUserInfo() != null && payload.getUserInfo().getLogininfo() != null){
                    //载荷数据非空，表示已登录，直接放行
                    return chain.filter(exchange);
                }
            }
            return noLogin(response);
        }catch (ExpiredJwtException e){
            e.printStackTrace();
            return noLogin(response);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Mono.empty();
    }

    private Mono<Void> noLogin(ServerHttpResponse response) {
        DataBuffer buffer;
        try{
            //载荷数据为空，表示未登录，返回前端一个noLogin
            byte[] bytes = JSON.toJSONString(JsonResult.error("noLogin")).getBytes("utf-8");
            buffer = response.bufferFactory().wrap(bytes);
            //设置完成相应，不会继续执行后面的filter
            //response.setComplete();
            //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            //把结果写给客户端
            return response.writeWith(Mono.just(buffer));
        }catch (Exception e){
            e.printStackTrace();
        }
        return Mono.empty();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
